package com.example.smssender;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;

/**
 * 短信格式列表页面
 */
public class SmsTemplateListActivity extends AppCompatActivity {
    
    public static final String EXTRA_SELECT_MODE = "select_mode";
    public static final String RESULT_SELECTED_TEMPLATE = "selected_template";
    
    private RecyclerView recyclerView;
    private SmsTemplateAdapter adapter;
    private DataManager dataManager;
    private List<SmsTemplate> templates;
    private boolean isSelectMode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_template_list);
        
        dataManager = DataManager.getInstance(this);
        isSelectMode = getIntent().getBooleanExtra(EXTRA_SELECT_MODE, false);
        
        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(isSelectMode ? "选择短信格式" : "短信格式列表");
        }
        
        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // 初始化数据
        templates = new ArrayList<>();
        adapter = new SmsTemplateAdapter(templates, new SmsTemplateAdapter.OnTemplateClickListener() {
            @Override
            public void onTemplateClick(SmsTemplate template) {
                if (isSelectMode) {
                    // 选择模式：返回选中的模板
                    Intent result = new Intent();
                    result.putExtra(RESULT_SELECTED_TEMPLATE, template);
                    setResult(RESULT_OK, result);
                    finish();
                } else {
                    // 普通模式：编辑模板
                    editTemplate(template);
                }
            }

            @Override
            public void onTemplateLongClick(SmsTemplate template) {
                if (!isSelectMode) {
                    // 长按删除
                    deleteTemplate(template);
                }
            }
        });
        recyclerView.setAdapter(adapter);
        
        // 添加按钮
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createNewTemplate();
            }
        });
        
        // 加载数据
        loadTemplates();
        
        // 处理返回键（使用新的 API）
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                handleBackPressed();
            }
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        loadTemplates();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // 处理返回按钮
            handleBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void handleBackPressed() {
        if (isSelectMode) {
            // 选择模式：返回时设置取消结果
            setResult(RESULT_CANCELED);
        }
        finish();
    }
    
    private void loadTemplates() {
        templates.clear();
        templates.addAll(dataManager.getSmsTemplates());
        adapter.notifyDataSetChanged();
    }
    
    private void createNewTemplate() {
        Intent intent = new Intent(this, SmsTemplateEditActivity.class);
        startActivity(intent);
    }
    
    private void editTemplate(SmsTemplate template) {
        Intent intent = new Intent(this, SmsTemplateEditActivity.class);
        intent.putExtra(SmsTemplateEditActivity.EXTRA_TEMPLATE_ID, template.getId());
        startActivity(intent);
    }
    
    private void deleteTemplate(SmsTemplate template) {
        new android.app.AlertDialog.Builder(this)
            .setTitle("删除短信格式")
            .setMessage("确定要删除短信格式 \"" + template.getTitle() + "\" 吗？")
            .setPositiveButton("删除", (dialog, which) -> {
                dataManager.deleteSmsTemplate(template.getId());
                loadTemplates();
                Toast.makeText(this, "已删除", Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }
}
